import re

from sqlalchemy import Column, Integer, String, CHAR, DateTime, Float, desc, text, DECIMAL
from sqlalchemy.dialects.mysql import LONGTEXT

from models.orders_info import orders_info
from models.base import db
from datetime import datetime

from models.base import Base
from models.sentence import Sentence
from models.sentence_word import SentenceWord


class sentence_detail(Base):
    __tablename__ = 'sentence_detail'
    id = Column(Integer, primary_key=True, autoincrement=True)
    order_number = Column(String(30), nullable=False)
    sentence_index = Column(CHAR(8), nullable=False)
    original_content = Column(String(500), nullable=False)
    similar_content = Column(String(2000), default='佚名')
    rate = Column(DECIMAL(5, 2), default=0)
    source = Column(String(250), default=0)
    title = Column(String(80), default=0)
    create_time = Column('create_time', Integer)
    author = Column(String(50), default='未知')
    url = Column(String(800), default='')
    check_id = Column(Integer, default=0)

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    @classmethod
    def get_sentence_index(cls, order_number):
        index = []
        result = db.execute(
            text('select DISTINCT(sentence_index) from sentence_detail where order_number = :order_number'),
            {'order_number': order_number}).fetchall()
        for i in result:
            index.append(i[0])
        return index

    @classmethod
    def get_top_rate(cls, order_number, check_id):
        sentences = db.query(cls).filter_by(order_number=order_number, check_id=check_id).order_by(
            desc('rate')).limit(15).all()
        return sentences

    def top_rate(self, order_number):
        if order_number[0] == '8':
            sentence_indexs = db.query(SentenceWord).filter(SentenceWord.is_similar > 0).filter(
                SentenceWord.order_number == order_number).all()
        else:
            sentence_indexs = db.query(Sentence).filter(Sentence.is_similar > 0).filter(
                Sentence.order_number == order_number).all()
        red_data = [[], []]
        orange_data = [[], []]
        for item in sentence_indexs:
            sentence = db.query(sentence_detail).filter_by(order_number=order_number).filter_by(
                check_id=item.check_id).order_by(
                desc('rate')).limit(1).first()
            if sentence.rate * 100 > 70:
                red_data[0].append(int(sentence.sentence_index))
                red_data[1].append(sentence.rate * 100)
            else:
                orange_data[0].append(int(sentence.sentence_index))
                orange_data[1].append(sentence.rate * 100)
        return orange_data, red_data

    def count_zh(self, str):
        count = 0
        zh = ''
        for s in str:
            if '\u4e00' <= s <= '\u9fa5':
                count += 1
                zh += s
        return count

    def getSingleAuthor(self, authors):
        res = []
        author_list = re.split("[， ；;,、]", authors.strip())
        for item in author_list:
            if self.count_zh(item) > 1:
                res.append(item)
        if res == []:
            res.append('佚名')
        return res

    def internetData(self, order_number):
        article_info = db.query(orders_info).filter_by(order_number=order_number).first()
        max_charsum = article_info.chars_sum
        authors = self.getSingleAuthor(article_info.author)
        if order_number[0] == '8':
            sentences = db.query(SentenceWord).filter_by(order_number=order_number).filter(
                SentenceWord.is_similar > 0).all()
        else:
            sentences = db.query(Sentence).filter_by(order_number=order_number).filter(
                Sentence.is_similar > 0).all()
        sources = []
        for item in sentences:
            datas = db.query(sentence_detail).filter_by(order_number=order_number).filter_by(
                sentence_index=item.sentence_index).order_by(
                desc('rate')).limit(2).all()
            for data in datas:
                sources.append(data)
        keys = []
        internetdata = {}
        localdata = {}
        internet = []
        local = []
        for item in sources:
            if item.source in ['互联网', '互联网文档库']:
                if f'《{item.title}》- 佚名 -{item.source}' not in keys:
                    keys.append(f'《{item.title}》- 佚名 -{item.source}')
                    internetdata[f'《{item.title}》- 佚名 -{item.source}'] = round(
                        (len(item.original_content) / max_charsum) * 100, 2)
                else:
                    internetdata[f'《{item.title}》- 佚名 -{item.source}'] += round(
                        (len(item.original_content) / max_charsum) * 100, 2)
            else:
                if item.author != '佚名' or item.source == '大学生论文联合对比库':
                    if item.source == '大学生论文联合对比库':
                        title = item.title
                        if len(item.title) < 5:
                            title = '大学生论文联合对比库'
                        if f'《{title}》- {item.author} - {item.source}' not in keys:
                            keys.append(f'《{title}》- {item.author} - {item.source}')
                            localdata[f'《{title}》- {item.author} - {item.source}'] = round(
                                (len(item.original_content) / max_charsum) * 100, 2)
                        else:
                            localdata[f'《{title}》- {item.author} - {item.source}'] += round(
                                (len(item.original_content) / max_charsum) * 100, 2)
                    else:
                        for author in authors:
                            if author in item.author:
                                if f'《{item.title}》- {item.author} -{item.source}  (本人已发表)' not in keys:
                                    keys.append(f'《{item.title}》- {item.author} -{item.source}  (本人已发表)')
                                    localdata[f'《{item.title}》- {item.author} -{item.source}  (本人已发表)'] = round(
                                        (len(item.original_content) / max_charsum) * 100, 2)
                                else:
                                    localdata[f'《{item.title}》- {item.author} -{item.source}  (本人已发表)'] += round(
                                        (len(item.original_content) / max_charsum) * 100, 2)
                            else:
                                if '学位论文' in item.author:
                                    if f'《{item.title}》- {item.author} -{item.source} (学位论文)' not in keys:
                                        keys.append(f'《{item.title}》- {item.author} -{item.source} (学位论文)')
                                        localdata[f'《{item.title}》- {item.author} -{item.source} (学位论文)'] = round(
                                            (len(item.original_content) / max_charsum) * 100, 2)
                                    else:
                                        localdata[f'《{item.title}》- {item.author} -{item.source} (学位论文)'] += round(
                                            (len(item.original_content) / max_charsum) * 100, 2)
                                else:
                                    if f'《{item.title}》- {item.author} -{item.source}(期刊)' not in keys:
                                        keys.append(f'《{item.title}》- {item.author} -{item.source}(期刊)')
                                        localdata[f'《{item.title}》- {item.author} -{item.source}(期刊)'] = round(
                                            (len(item.original_content) / max_charsum) * 100, 2)
                                    else:
                                        localdata[f'《{item.title}》- {item.author} -{item.source}(期刊)'] += round(
                                            (len(item.original_content) / max_charsum) * 100, 2)
                else:
                    if f'《{item.title}》- 硕博 -{item.source}' not in keys:
                        keys.append(f'《{item.title}》- 硕博 -{item.source}')
                        localdata[f'《{item.title}》- 硕博 -{item.source}'] = round(
                            (len(item.original_content) / max_charsum) * 100, 2)
                    else:
                        localdata[f'《{item.title}》- 硕博 -{item.source}'] += round(
                            (len(item.original_content) / max_charsum) * 100, 2)
        for key, value in internetdata.items():
            rate = 100 if round(value, 1) > 100 else round(value, 1)
            internet.append({
                'source': key,
                'rate': rate
            })
        internet.sort(key=lambda k: (k.get('rate', 0)), reverse=True)
        for key, value in localdata.items():
            rate = 100 if round(value, 1) > 100 else round(value, 1)
            local.append({
                'source': key,
                'rate': rate
            })
        local.sort(key=lambda k: (k.get('rate', 0)), reverse=True)
        return internet, local
